<template>
  <n-modal v-model:show="visible" title="新增按钮" display-directive="if" :bordered="false" preset="card" class="w-400px"  size="small" :closable="false" >
    <n-space vertical >
      <n-space>
        <n-tag type="info" class="mt-1 w-100px" > 权限前缀 </n-tag>
        <n-input v-model:value="prePermission" placeholder="xxx:xxx" style="width: 200px;" />
      </n-space>
      <n-space v-for="item, i in formData" >
        <n-input :ref="inputKeyRef" v-model:value="formData[i].name" placeholder="按钮名称"  style="width: 100px;" @keyup.enter.native="handleAddExtra" />
        <n-input v-model:value="formData[i].permission" placeholder="权限字符" style="width: 200px;"  @keyup.enter.native="handleAddExtra"/>
        <n-popconfirm @positive-click="() => handleDeleteItemRow(i)" @negative-click="() => { }">
          <template #trigger>
            <n-button strong secondary circle type="error" size="small" class="mt-1">
              <template #icon>
                <svg-icon icon="material-symbols:delete" />
              </template>
            </n-button>
          </template>
          是否确认删除当前行数据
        </n-popconfirm>
      </n-space>
      <n-space class="mt-4">
        <n-button @click="handleAddExtra">添加一行</n-button>
        <n-button type="primary" @click="handleSubmit">提交</n-button>
      </n-space>
    </n-space>

  </n-modal>


</template>

<script setup lang="ts">
import { fetchBatchAddMenuBtn } from '@/service/api/sys/menu';
import { InputInst } from 'naive-ui';
import {  ref , computed,  watch, nextTick  } from 'vue';
interface DataSource {
  name:string,permission:string
}
type Props = {
  visible:boolean,
  pId?:Common.IdType | null
}
const props = defineProps<Props>()
const visible = defineModel<boolean>('visible', {
  default: false
});
const pId = computed(() => props.pId || null);

interface Emits {
  (e: 'submitted'): void;
}
const emit = defineEmits<Emits>();

const formData = ref<DataSource[]>(initFormData())
  const inputKeyRefList =ref<InputInst[]>([])

  const inputKeyRef = (el:any)=>{
	if(el)inputKeyRefList.value.push(el)
}
const prePermission = ref<string>('')
function handleAddExtra() {
	if(!validItemList()){
		window.$message?.error("存在不符合规范的数据，请处理后，再进行新增操作")
		return
	}
	formData.value.push({name:"",permission:""})
	nextTick(()=>{
		inputKeyRefList.value[inputKeyRefList.value.length-1]?.focus()
	})

}
function validItemList():boolean{
	const temps =  formData.value
	for(let i = 0 ; i<temps.length ; i++){
		const temp = temps[i]
		if(!(temp.name && temp.permission)){
			return false
		}
	}
	return true;
}
function handleDeleteItemRow(i: number) {
	formData.value.splice(i,1)
}
function initFormData():DataSource[]{
  return [{name:'',permission:''}]
}
async function handleSubmit(){
  if(validItemList()){
    const submitFormData = formData.value.map(it=>({name:it.name,permission:prePermission.value + it.permission}))
    const {error} = await fetchBatchAddMenuBtn(pId.value!,submitFormData)
    if(!error){
      window.$message?.success("新增成功")
      visible.value = false
      emit('submitted')
    }
  }
}
watch(visible, () => {
  if (visible.value) {
  }else{
    formData.value = initFormData()
  }
});

</script>
